﻿
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace My.Core.Common.Helper
{
    //系统默认配置节点
    //第一种方式  HttpContext.RequestServices.GetService
    //var builder = new ConfigurationBuilder()
    //           .SetBasePath(Directory.GetCurrentDirectory())
    //           .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    //.AddEnvironmentVariables();
    //var settings = new Appsettings();
    //IConfigurationRoot configuration = builder.Build();
    //configuration.Bind("Audience",settings);
    //services.AddSingleton(settings);
    //第二种 
    //IOptions<Appsettings> options  
    // services.Configure<Appsettings>(Configuration.GetSection("Audience"));
    //   services.Configure<Appsettings>(Configuration);
    //HttpContext.RequestServices.GetService
    //  services.AddScoped(resolver =>
    //  resolver.GetRequiredService<IOptions<Appsettings>>().Value);
    public class Appsettings
    {

        public Jwt Jwt { get; set; }
        public ConnectionStrings ConnectionStrings { get; set; }


    }
    /// <summary>
    /// jwt
    /// </summary>
    public class Jwt
    {
        public string Secret { get; set; }
        public string SecretFile { get; set; }
        public string Issuer { get; set; }
        public string Audience { get; set; }
    }
    public class ConnectionStrings
    {
        public string SqlServerConnection { get; set; }
    }


    /// <summary>
    /// appsettings.json操作类
    /// </summary>
    public class AppsettingsHelper
    {
        static IConfiguration Configuration { get; set; }

        /// <summary>
        /// 默认构造
        /// </summary>
        /// <param name="contentPath"></param>
        public AppsettingsHelper(string contentPath)
        {

            string Path = "appsettings.json";
            
            Configuration = new ConfigurationBuilder()
               .SetBasePath(contentPath)
               .Add(new JsonConfigurationSource { Path = Path, Optional = false, ReloadOnChange = true })
               .Build();


        }

        /// <summary>
        /// 节点下值
        /// </summary>
        /// <param name="sections">节点配置</param>
        /// <returns></returns>
        public static string AppsettingValue(params string[] sections)
        {
            try
            {

                if (sections.Any())
                {
                    return Configuration[string.Join(":", sections)];
                }
            }
            catch (Exception) { }

            return "";
        }
    }
}
